package com.itheima.sharding.alg;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;

/**
 * 定义范围匹配库
 * 接口中的泛型类型与分片键的类型一致 （user_id -->bigint -->long）
 * 定义当sql分片键使用BETWEEN的时候，会调用该方法
 */
public class MyRangeShardingAlgorithm4Db implements RangeShardingAlgorithm<Long> {
    /**
     *
     * @param collection 配置文件中的数据源集合 ds1 ds2
     * @param rangeShardingValue 分片值 即 BETWEEN user_id BETWEEN 1 AND 10
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        //获取逻辑表名
        String logicTableName = rangeShardingValue.getLogicTableName();
        //1.获取分片键名
        String shardingColumn = rangeShardingValue.getColumnName();
        //2.获取分片键值范围
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        //3.根据分片键值范围，进行范围匹配
        if (valueRange.hasLowerBound()){//存在下限
            Long l = valueRange.lowerEndpoint();
        }
        if (valueRange.hasUpperBound()){//存在上限
            Long u = valueRange.upperEndpoint();
        }
        return collection;
    }
}
